package com.smartStatus.core.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import io.minio.MinioClient;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName : FileUtils
 * @Author : lby
 * @Date: 2020/12/1 14:00
 * @Description : 文件处理工具类
 */
@RequiredArgsConstructor
@Component
public class FileUtils implements InitializingBean {
    /**
     * 连接url
     */
    private final String minioUrl = "http://47.112.237.64:9000";

    /**
     * minlo用户名
     */
    private final String minioUser = "minioadmin";

    /**
     * minio密码
     */
    private final String minioPassword = "minioadmin";

    /**
     * 全局桶名称
     */
    private final String bucketName = "images";
    private MinioClient minioClient;

    /**
     * 创建minio桶
     * bucket
     */
    @SneakyThrows
    public void createBucket(String bucketName) {
        if (!minioClient.bucketExists(bucketName)) {
            minioClient.makeBucket(bucketName);
        }
    }

    /**
     * 上传文件
     */
    @SneakyThrows
    public void uploadFile(MultipartFile file, String fileName) throws Exception {
//        根据桶名称创建桶，将文件存储在桶中
        createBucket(bucketName);
        minioClient.putObject(bucketName, fileName, file.getInputStream(), (long) file.getInputStream().available(), null, null, "multipart/form-data");
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.hasText(minioUrl, "Minio url 为空");
        Assert.hasText(minioUser, "Minio accessKey为空");
        Assert.hasText(minioPassword, "Minio secretKey为空");
        this.minioClient = new MinioClient(minioUrl, minioUser, minioPassword);
    }

    /**
     * 获取文件
     */
    @SneakyThrows
    public InputStream getFile(String bucketName, String fileName) throws Exception {
        InputStream object = minioClient.getObject(bucketName, fileName);
        return object;
    }

    @SneakyThrows
    public String getFileUrl(String bucketName, String fileName) {
        String objectUrl = minioClient.getObjectUrl(bucketName, fileName);
        return objectUrl;
    }


}
